<?php

namespace App\Http\Controllers\Admin;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Org\code\Code;
use App\Model\User;
use Illuminate\Support\Facades\Crypt;

class LoginController extends Controller
{
    //后台登录页
    public function login() {
        return view('admin.login');
    }

    // 验证码
    public function code() {
        $code = new Code();
        return $code->code();
    }

    // 处理用户登录方法
    public function doLogin(Request $request) {
        // 接受表单信息
        $input = $request->except('_token');
        // 表单验证
        // $validator = Validator::make('验证的数据', ‘验证的规则’, ‘错误的提示’);
        $rule = [
            'username' => 'required|between:4,18',
            'password' => 'required|between:6,18|alpha_dash',
        ];

        $msg = [
            'username.required'   => '用户名必须输入',
            'username.between'    => '用户名必须在4-18位之间',
            'password.required'   => '密码必须输入',
            'password.between'    => '密码必须在4-18位之间',
            'password.alpha_dash' => '密码必须是数字字母下划线',
        ];

        $validator = Validator::make($input, $rule, $msg);

        if ($validator->fails()) {
            return redirect('admin/login')
                ->withErrors($validator)
                ->withInput();
        }

        // 验证验证码
        if(strtolower($input['code']) != strtolower(session()->get('code'))) {
            return redirect('admin/login')->with('errors', '验证码错误');
        }

        // 后台验证
        $user = User::where('user_name',$input['username'])->first();

        if(!$user){
            return redirect('admin/login')->with('errors', '用户不存在');
        }

        if($input['password'] != Crypt::decrypt($user->user_pass)){
            return redirect('admin/login')->with('errors', '密码错误');
        }

        // 保存用户信息到session
        session()->put('user',$user);

        // 跳转到后台首页
        return redirect('admin/index');
    }

    // 后台欢迎页面
    public function welcome(){
        return view('admin.welcome');
    }

    // 退出登录
    public function logout() {
        session()->flush();
        return redirect('admin/login');
    }
}
